#include "Client.h"
#include "ui_Client.h"
#include <QMessageBox>
#include <QBitmap>
#include <QStyleOption>
#include "mymessagebox.h"

Client::Client(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Client)
    , socket(new QTcpSocket(this))  // 初始化 TCP socket
{
    ui->setupUi(this);

    // 隐藏原生标题栏
    setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);

    // 防止窗口背景透明
    setAttribute(Qt::WA_TranslucentBackground, false);

    // 点击关闭按钮关闭窗口
    connect(ui->closeButton, &QPushButton::clicked, this, &Client::close);

    ui->password->setEchoMode(QLineEdit::Password);

    // 连接服务器返回数据的槽函数
    connect(socket, &QTcpSocket::readyRead, this, &Client::onReadyRead);
}

Client::~Client()
{
    delete ui;
}

// 实现窗口拖动功能
void Client::mousePressEvent(QMouseEvent *event)
{
    // 检查是否点击了自定义标题栏
    if (event->button() == Qt::LeftButton && event->pos().y() <= 60) {
        m_isTitleBarClicked = true;
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    } else {
        m_isTitleBarClicked = false;
        // 让事件继续传播，确保其他控件能响应点击事件
        QWidget::mousePressEvent(event);
    }
}

void Client::mouseMoveEvent(QMouseEvent *event)
{
    // 只有在点击了标题栏之后才允许拖动
    if (m_isTitleBarClicked && (event->buttons() & Qt::LeftButton)) {
        move(event->globalPos() - m_dragPosition);
        event->accept();
    } else {
        // 让事件继续传播，确保其他控件能响应移动事件
        QWidget::mouseMoveEvent(event);
    }
}

void Client::paintEvent(QPaintEvent *event)
{
    // 1. 绘制样式（QSS）
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); // 绘制样式

    // 2. 设置掩码，约定 painter 绘制区域
    QBitmap bmp(this->size());
    bmp.fill(Qt::white); // 填充 bitmap

    QPainter painter(&bmp);
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::black); // 掩码值
    painter.drawRoundedRect(bmp.rect(), 30, 30); // 在 bitmap 中绘制圆角矩形

    // 设置掩码以确定本控件可绘制区域
    setMask(bmp);

    // 调用基类的 paintEvent
    QWidget::paintEvent(event);
}

void Client::on_enroll_clicked()
{
    Enroll *enroll = new Enroll(this);
    enroll->show();
    this->hide();
}


void Client::on_login_clicked()
{
    employeeId = ui->num->text();
    QString password = ui->password->text();

    if (employeeId.isEmpty() || password.isEmpty()) {
        // QMessageBox::warning(this, "错误", "请填写工号和密码");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("请填写工号和密码");
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    sendDataToServer(employeeId, password);  // 发送工号和密码到服务器
}

void Client::sendDataToServer(const QString &employeeId, const QString &password)
{
    QString dataToSend = QString("%1|%2").arg(employeeId).arg(password);
    socket->connectToHost("127.0.0.1", 12346);  // 连接服务器
    if (socket->waitForConnected(3000)) {
        socket->write(dataToSend.toUtf8());  // 发送工号和密码
    } else {
        // QMessageBox::warning(this, "错误", "无法连接到服务器");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法连接到服务器");
        msgBox.setButton("确定");
        msgBox.exec();
    }
}

void Client::onReadyRead()
{
    QByteArray data = socket->readAll();  // 读取服务器返回的数据
    QString response = QString::fromUtf8(data);

    handleServerResponse(response);  // 处理服务器响应
}

void Client::handleServerResponse(const QString &response)
{
    if (response == "UNVERIFIED_EMPLOYEE") {
        // QMessageBox::warning(this, "错误", "该员工未认证");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("该员工未认证");
        msgBox.setButton("确定");
        msgBox.exec();
    } else if (response == "PASSWORD_ERROR") {
        // QMessageBox::warning(this, "错误", "密码错误");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("密码错误");
        msgBox.setButton("确定");
        msgBox.exec();
    } else if (response == "LOGIN_SUCCESS") {
        // QMessageBox::information(this, "成功", "登录成功");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("成功");
        msgBox.setText("登录成功");
        msgBox.setButton("确定");
        msgBox.exec();

        // 直接在构造函数中传递工号
        Mainpage *mainPage = new Mainpage(employeeId, this);
        mainPage->show();
        this->hide();
    } else {
        // QMessageBox::warning(this, "错误", "未知错误");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("未知错误");
        msgBox.setButton("确定");
        msgBox.exec();
    }
}
